<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-logo">
        <a href="#">
          <img src="../../assets/logo.png" alt="logo">
        </a>
      </div>
      <div class="login-form">
        <h3>用户登录</h3>
        <el-form ref="form" :model="loginForm" :rules="rules" label-position="left" label-width="0">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input v-model="loginForm.captcha" placeholder="请输入验证码（点击图片可以刷新）"></el-input>
          </el-form-item>
          <el-form-item>
            <img :src="captchaCode" alt="Captcha"
                 @click="showCaptcha">
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="doLogin()" :loading="loading1">登录</el-button>
            <el-button type="success" @click="goRegister()" :loading="loading2">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {getCaptcha, login} from '@/api/login.js'
import {setToken} from '@/utils/auth'

export default {
  data() {
    return {
      captchaCode: '',
      captchaURL: 'http://localhost:28080/server/basic/get-captcha',
      loginForm: {
        username: '',
        password: '',
        captcha: '',
      },
      rules: {
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        captcha: [{required: true, message: '请输入验证码', trigger: 'blur'}]
      },
      loading1: false,
      loading2: false,
    }
  },
  mounted() {
    // this.captchaURL = 'http://localhost:28080/server/basic/get-captcha' + '?' + Math.random();
    this.showCaptcha();
  },
  methods: {
    showCaptcha() {
      getCaptcha().then(res => {
        // console.log(res)
        return (
            "data:image/png;base64," +
            btoa(
                new Uint8Array(res).reduce( //后端是直接以流的方式写过来的，res似乎就是data本身
                    (data, byte) => data + String.fromCharCode(byte),
                    ""
                )
            )
        );
      }).then((data) => {
        this.captchaCode = data; //将base64编码赋值给imgCode
      });
    },
    doLogin() {
      this.$refs.form.validate(valid => {
        if (valid) {
          //加载登录动画，登录中的圆圈会转起来
          this.loading1 = true
          //发起网络请求，登录，如果登录成功，跳转到主界面，特别注意4月11日这天后端接口发生了变化，不能生搬硬套上节课的接口！
          login(this.loginForm).then(res => {
            this.loading1 = false
            if (res['code'] !== 200) {
              this.$message.error(res['msg'])
              this.showCaptcha()
            }
            // setToken(res.data.token)
            // setToken(res['data']['accessToken'])
            setToken(res['data'])
            this.$router.push({path: '/'})
            window.location.reload() // 成功登录后强制刷新，以重新获取路由。
            /**
             *  重新登录另一个角色的账号时会出现路由丢失的情况
             *  因为本质上只是组件之间的切换，不会从头执行代码
             *  所以也就不会重新请求另一个角色的路由信息
             */
          }).catch(() => {
            /*            // 登录失败，显示错误提示
                        this.$message.error('发生异常')
                        this.loading1 = false*/
            console.log("登录时出现异常")
          })
        }
      })
    },
    goRegister() {
      this.$router.push('/register');
      this.loading2 = true
    }
  }
}
</script>

<style lang="scss">
.login-container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  .login-box {
    width: 400px;
    //height: 400px;
    border-radius: 5px;
    box-shadow: 0px 0px 10px #ccc;

    .login-logo {
      height: 100px;
      display: flex;
      justify-content: center;
      align-items: center;

      img {
        height: 80%;
      }
    }

    .login-form {
      padding: 20px;

      h3 {
        font-size: 24px;
        margin-bottom: 20px;
        text-align: center;
      }
    }
  }
}
</style>
